package com.situ.mall.web.controller;

import com.category.spi.model.CategoryTreeDTO;
import com.mall.common.util.JsonResult;
import com.mall.user.model.dto.user.UserLoginRequest;
import com.mall.user.model.dto.user.UserRegisterRequest;
import com.mall.user.model.vo.LoginUserVO;
import com.situ.mall.web.service.CategoryFeignService;
import com.situ.mall.web.service.OrderFeignService;
import com.situ.mall.web.service.UserFeignService;
import com.situ.mall.web.service.FavoriteFeignService;
import com.situ.mall.web.service.AddressFeignService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.user.model.vo.UserFavoriteVO;
import com.mall.user.model.vo.AddressVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import java.util.List;

/**
 * 用户控制器
 */
@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserFeignService userFeignService;

    @Autowired
    private CategoryFeignService categoryFeignService;
    
    @Autowired
    private OrderFeignService orderFeignService;
    
    @Autowired
    private FavoriteFeignService favoriteFeignService;
    
    @Autowired
    private AddressFeignService addressFeignService;

    /**
     * 登录页面
     */
    @GetMapping("/login")
    public String loginPage(Model model) {
        // 获取分类数据（用于导航）
        try {
            JsonResult<List<CategoryTreeDTO>> categoryResult = categoryFeignService.getCategoryTree(1);
            if (categoryResult != null && categoryResult.getData() != null) {
                model.addAttribute("categories", categoryResult.getData());
            }
        } catch (Exception e) {
            log.error("获取分类数据失败", e);
            // 设置默认空数据
            model.addAttribute("categories", java.util.Collections.emptyList());
        }
        return "login";
    }

    /**
     * 处理用户登录
     */
    @PostMapping("/login")
    @ResponseBody
    public JsonResult<?> login(@RequestParam("account") String account,
                              @RequestParam("password") String password,
                              @RequestParam(value = "rememberMe", defaultValue = "false") Boolean rememberMe,
                              HttpServletRequest request) {
        try {
            if (!StringUtils.hasText(account) || !StringUtils.hasText(password)) {
                return JsonResult.fail("账号和密码不能为空");
            }

            UserLoginRequest loginRequest = new UserLoginRequest();
            loginRequest.setAccount(account);
            loginRequest.setPassword(password);
            loginRequest.setRememberMe(rememberMe);

            JsonResult<LoginUserVO> result = userFeignService.userLogin(loginRequest);
            if (result != null && result.isSuccess() && result.getData() != null) {
                // 将用户信息存储到Session中
                HttpSession session = request.getSession();
                    session.setAttribute("currentUser", result.getData());
                session.setAttribute("isLoggedIn", true);
                
                log.info("用户登录成功: account={}, sessionId={}", account, session.getId());
                return JsonResult.success("登录成功");
            } else {
                return JsonResult.fail(result != null ? result.getMsg() : "登录失败");
            }

        } catch (Exception e) {
            log.error("用户登录失败: account={}", account, e);
            return JsonResult.fail("登录失败: " + e.getMessage());
        }
    }

    /**
     * 用户注册页面
     */
    @GetMapping("/register")
    public String registerPage() {
        return "redirect:/user/login";
    }

    /**
     * 处理用户注册
     */
    @PostMapping("/register")
    @ResponseBody
    public JsonResult<?> register(@RequestBody RegisterRequest registerReq) {
        try {
            if (!StringUtils.hasText(registerReq.getUsername()) || !StringUtils.hasText(registerReq.getPassword())) {
                return JsonResult.fail("用户名和密码不能为空");
            }

            if (!registerReq.getPassword().equals(registerReq.getCheckPassword())) {
                return JsonResult.fail("两次输入的密码不一致");
            }

            UserRegisterRequest registerRequest = new UserRegisterRequest();
            registerRequest.setUsername(registerReq.getUsername());
            registerRequest.setPassword(registerReq.getPassword());
            registerRequest.setCheckPassword(registerReq.getCheckPassword());

            JsonResult<Long> result = userFeignService.userRegister(registerRequest);
            if (result != null && result.isSuccess()) {
                log.info("用户注册成功: username={}, userId={}", registerReq.getUsername(), result.getData());
                return JsonResult.success("注册成功，请登录");
            } else {
                return JsonResult.fail(result != null ? result.getMsg() : "注册失败");
            }

        } catch (Exception e) {
            log.error("用户注册失败: username={}", registerReq.getUsername(), e);
            return JsonResult.fail("注册失败: " + e.getMessage());
        }
    }

    /**
     * 用户注销
     */
    @PostMapping("/logout")
    @ResponseBody
    public JsonResult<?> logout(HttpServletRequest request) {
        try {
        HttpSession session = request.getSession(false);
            if (session != null) {
                String sessionId = session.getId();
                session.invalidate();
                log.info("用户注销成功: sessionId={}", sessionId);
                
                // 也调用后端注销接口
                userFeignService.userLogout();
            }
            return JsonResult.success("注销成功");
        } catch (Exception e) {
            log.error("用户注销失败", e);
            return JsonResult.fail("注销失败");
        }
    }

    /**
     * 个人中心页面
     */
    @GetMapping("/my-account")
    public String myAccount(Model model, HttpServletRequest request) {
        try {
            // 检查登录状态
            LoginUserVO currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return "redirect:/user/login";
            }

            // 获取分类数据（用于导航）
            JsonResult<List<CategoryTreeDTO>> categoryResult = categoryFeignService.getCategoryTree(1);
            if (categoryResult != null && categoryResult.getData() != null) {
                model.addAttribute("categories", categoryResult.getData());
            }

            // 获取用户订单列表
            ResponseEntity<JsonResult<?>> ordersResult = orderFeignService.getUserOrders(
                    1, 10, currentUser.getId(), null);
            if (ordersResult.getBody() != null && ordersResult.getBody().isSuccess()) {
                model.addAttribute("orders", ordersResult.getBody().getData());
            }

            // 获取用户等级信息和统计数据
            UserLevelInfo levelInfo = calculateUserLevel(currentUser);
            model.addAttribute("levelInfo", levelInfo);

            model.addAttribute("currentUser", currentUser);
            model.addAttribute("isLoggedIn", true);

        } catch (Exception e) {
            log.error("个人中心页面数据加载失败", e);
        }

        return "my-account";
        }
        
    /**
     * 我的收藏页面
     */
    @GetMapping("/my-favorites")
    public String myFavorites(Model model, HttpServletRequest request,
                             @RequestParam(defaultValue = "1") int page,
                             @RequestParam(defaultValue = "10") int size) {
        try {
            LoginUserVO currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return "redirect:/user/login";
    }

            // 获取分类数据（用于导航）
            JsonResult<List<CategoryTreeDTO>> categoryResult = categoryFeignService.getCategoryTree(1);
            if (categoryResult != null && categoryResult.getData() != null) {
                model.addAttribute("categories", categoryResult.getData());
            }

            // 获取用户收藏列表
            JsonResult<Page<UserFavoriteVO>> favoritesResult = favoriteFeignService.getUserFavorites(page, size);
            if (favoritesResult != null && favoritesResult.isSuccess()) {
                model.addAttribute("favorites", favoritesResult.getData());
            }

            model.addAttribute("currentUser", currentUser);

        } catch (Exception e) {
            log.error("收藏页面数据加载失败", e);
        }

        return "my-favorites"; // 需要创建这个模板
    }

    /**
     * 地址管理页面
     */
    @GetMapping("/my-addresses")
    public String myAddresses(Model model, HttpServletRequest request) {
        try {
            LoginUserVO currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return "redirect:/user/login";
            }

            // 获取分类数据（用于导航）
            JsonResult<List<CategoryTreeDTO>> categoryResult = categoryFeignService.getCategoryTree(1);
            if (categoryResult != null && categoryResult.getData() != null) {
                model.addAttribute("categories", categoryResult.getData());
        }
        
            // 获取用户地址列表
            JsonResult<List<AddressVO>> addressesResult = addressFeignService.getUserAddresses();
            if (addressesResult != null && addressesResult.isSuccess()) {
                model.addAttribute("addresses", addressesResult.getData());
            }
            
            // 获取默认地址
            JsonResult<AddressVO> defaultAddressResult = addressFeignService.getDefaultAddress();
            if (defaultAddressResult != null && defaultAddressResult.isSuccess()) {
                model.addAttribute("defaultAddress", defaultAddressResult.getData());
            }

            model.addAttribute("currentUser", currentUser);

        } catch (Exception e) {
            log.error("地址管理页面数据加载失败", e);
        }
        
        return "my-addresses"; // 需要创建这个模板
    }

    /**
     * 删除地址
     */
    @PostMapping("/address/delete")
    @ResponseBody
    public JsonResult<?> deleteAddress(@RequestParam("addressId") String addressId,
                                      HttpServletRequest request) {
        try {
            LoginUserVO currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return JsonResult.fail("请先登录");
            }

            JsonResult<Boolean> result = addressFeignService.deleteAddress(addressId);
            if (result != null && result.isSuccess()) {
                return JsonResult.success("地址删除成功");
            } else {
                return JsonResult.fail(result != null ? result.getMsg() : "地址删除失败");
            }

        } catch (Exception e) {
            log.error("删除地址失败: addressId={}", addressId, e);
            return JsonResult.fail("删除地址失败: " + e.getMessage());
        }
    }

    /**
     * 设置默认地址
     */
    @PostMapping("/address/setDefault")
    @ResponseBody
    public JsonResult<?> setDefaultAddress(@RequestParam("addressId") String addressId,
                                          HttpServletRequest request) {
        try {
            LoginUserVO currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return JsonResult.fail("请先登录");
            }
            
            JsonResult<Boolean> result = addressFeignService.setDefaultAddress(addressId);
            if (result != null && result.isSuccess()) {
                return JsonResult.success("默认地址设置成功");
            } else {
                return JsonResult.fail(result != null ? result.getMsg() : "设置默认地址失败");
            }

        } catch (Exception e) {
            log.error("设置默认地址失败: addressId={}", addressId, e);
            return JsonResult.fail("设置默认地址失败: " + e.getMessage());
        }
    }

    /**
     * 从Session中获取当前用户
     */
    private LoginUserVO getCurrentUser(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            Object userInfo = session.getAttribute("currentUser");
            if (userInfo instanceof LoginUserVO) {
                return (LoginUserVO) userInfo;
            }
        }
        return null;
    }

    /**
     * 计算用户等级信息
     */
    private UserLevelInfo calculateUserLevel(LoginUserVO user) {
        UserLevelInfo levelInfo = new UserLevelInfo();
        
        // 设置当前等级信息
        Integer memberLevel = user.getMemberLevel();
        levelInfo.setCurrentLevel(memberLevel);
        levelInfo.setCurrentLevelName(getLevelName(memberLevel));
        levelInfo.setTotalSpent(user.getTotalSpent());
        levelInfo.setCurrentYearSpent(user.getCurrentYearSpent());
        
        // 计算下一等级所需金额
        if (memberLevel != null && memberLevel > 0) {
            levelInfo.setNextLevelName(getLevelName(memberLevel - 1));
            levelInfo.setNextLevelRequired(getNextLevelAmount(memberLevel));
            
            if (user.getTotalSpent() != null) {
                levelInfo.setProgressToNext(calculateProgress(user.getTotalSpent(), memberLevel));
            }
        } else {
            levelInfo.setNextLevelName("已达最高等级");
            levelInfo.setProgressToNext(100);
        }
        
        // 设置等级权益
        levelInfo.setLevelBenefits(getLevelBenefits(memberLevel));
        
        return levelInfo;
    }

    /**
     * 获取等级名称
     */
    private String getLevelName(Integer level) {
        if (level == null) return "普通会员";
        return switch (level) {
            case 0 -> "黑金会员";
            case 1 -> "白金会员";
            case 2 -> "普通会员";
            default -> "普通会员";
        };
    }

    /**
     * 获取下一等级所需金额
     */
    private java.math.BigDecimal getNextLevelAmount(Integer currentLevel) {
        return switch (currentLevel) {
            case 2 -> new java.math.BigDecimal("10000");  // 普通->白金需要1万
            case 1 -> new java.math.BigDecimal("50000");  // 白金->黑金需要5万
            default -> java.math.BigDecimal.ZERO;
        };
    }

    /**
     * 计算升级进度百分比
     */
    private Integer calculateProgress(java.math.BigDecimal totalSpent, Integer currentLevel) {
        java.math.BigDecimal required = getNextLevelAmount(currentLevel);
        if (required.compareTo(java.math.BigDecimal.ZERO) == 0) {
            return 100;
        }
        
        double progress = totalSpent.divide(required, 4, java.math.RoundingMode.HALF_UP)
                                  .multiply(new java.math.BigDecimal("100"))
                                  .doubleValue();
        return Math.min(100, (int) progress);
    }

    /**
     * 获取等级权益
     */
    private List<String> getLevelBenefits(Integer level) {
        if (level == null) level = 2;
        return switch (level) {
            case 0 -> List.of("专属客服", "免费包邮", "生日特权", "积分双倍", "专属优惠券");
            case 1 -> List.of("优先发货", "免费包邮", "积分1.5倍", "会员优惠券");
            case 2 -> List.of("基础积分", "新人优惠券");
            default -> List.of("基础积分");
        };
    }

    /**
     * 用户等级信息VO
     */
    public static class UserLevelInfo {
        private Integer currentLevel;
        private String currentLevelName;
        private String nextLevelName;
        private java.math.BigDecimal totalSpent;
        private java.math.BigDecimal currentYearSpent;
        private java.math.BigDecimal nextLevelRequired;
        private Integer progressToNext;
        private List<String> levelBenefits;

        // getters and setters
        public Integer getCurrentLevel() { return currentLevel; }
        public void setCurrentLevel(Integer currentLevel) { this.currentLevel = currentLevel; }

        public String getCurrentLevelName() { return currentLevelName; }
        public void setCurrentLevelName(String currentLevelName) { this.currentLevelName = currentLevelName; }

        public String getNextLevelName() { return nextLevelName; }
        public void setNextLevelName(String nextLevelName) { this.nextLevelName = nextLevelName; }

        public java.math.BigDecimal getTotalSpent() { return totalSpent; }
        public void setTotalSpent(java.math.BigDecimal totalSpent) { this.totalSpent = totalSpent; }

        public java.math.BigDecimal getCurrentYearSpent() { return currentYearSpent; }
        public void setCurrentYearSpent(java.math.BigDecimal currentYearSpent) { this.currentYearSpent = currentYearSpent; }

        public java.math.BigDecimal getNextLevelRequired() { return nextLevelRequired; }
        public void setNextLevelRequired(java.math.BigDecimal nextLevelRequired) { this.nextLevelRequired = nextLevelRequired; }

        public Integer getProgressToNext() { return progressToNext; }
        public void setProgressToNext(Integer progressToNext) { this.progressToNext = progressToNext; }

        public List<String> getLevelBenefits() { return levelBenefits; }
        public void setLevelBenefits(List<String> levelBenefits) { this.levelBenefits = levelBenefits; }
    }

    /**
     * 注册请求DTO
     */
    public static class RegisterRequest {
        private String username;
        private String password;
        private String checkPassword;

        // getters and setters
        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }

        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }

        public String getCheckPassword() { return checkPassword; }
        public void setCheckPassword(String checkPassword) { this.checkPassword = checkPassword; }
    }
} 